# -*- coding:utf-8 -*-
from __future__ import unicode_literals

from django.core.urlresolvers import reverse
from django.db import models
from wenlincms.core.fields import FileField
from wenlincms.core.models import Displayable, Ownable, RichText, Slugged
from wenlincms.generic.fields import CommentsField
from wenlincms.utils.models import upload_to

# 保存和删除的信号相关
from django.db.models.signals import post_save
from .signals import save_signal_func


class ArticlePost(Displayable, Ownable, RichText):
    categories = models.ManyToManyField("ArticleCategory",
                                        verbose_name="分类目录", blank=True, related_name="articleposts")
    allow_comments = models.BooleanField(verbose_name="是否允许评论", default=True)
    comments = CommentsField(verbose_name="评论")
    featured_image = FileField(verbose_name="封面图片",
                               upload_to=upload_to("article.ArticlePost.featured_image",
                                                   "article/featured_image"),
                               format="Image", null=True, blank=True)
    Displayable._meta.get_field('title').verbose_name = '标题'
    view_count = models.IntegerField('浏览次数', default=0, blank=True)

    class Meta:
        verbose_name = "文章"
        verbose_name_plural = "文章"
        db_table = 'article'

    def save(self, *args, **kwargs):
        self.audit_status = 1  # 默认的审核值
        super(ArticlePost, self).save(*args, **kwargs)

    def get_absolute_url(self):
        # url_name = "article_post_detail"
        # kwargs = {"slug": self.slug}
        url_name = "guan_news_text"
        kwargs = {"id": self.id or 'none'}
        return reverse(url_name, kwargs=kwargs)

    def category_list(self):
        from warnings import warn

        warn("article_post.category_list in templates is deprecated"
             "use article_post.categories.all which are prefetched")
        return getattr(self, "_categories", self.categories.all())


class ArticleCategory(Slugged):
    class Meta:
        verbose_name = "文章分类"
        verbose_name_plural = "文章分类"
        ordering = ("title",)
        db_table = 'article_category'

    @models.permalink
    def get_absolute_url(self):
        return ("article_post_list_category", (), {"category": self.slug})


# 连接信号接收函数
post_save.connect(save_signal_func, sender=ArticlePost, dispatch_uid="a8f634n92ffe")
